﻿using MySql.Data.MySqlClient;
using System;

namespace newBlog.inc.SqlINC
{
    public class sqlConnect
    {
        //定义数据库调用代码
        string url = @"data source=localhost;database=webdemo1;user id=sa;password=123456;pooling=true;;min pool size=5;max pool size=1024;connect timeout = 20;charset=utf8;";
        MySqlCommand cmd;
        public MySqlConnection connect()
        {
            MySqlConnection conn = new MySqlConnection(url);
            try
            {
                conn.Open();
                return conn;
            }
            catch
            {
                return null;
            }

        }
        public int AddDelUp(string sql)
        {
            //执行增删改操作并且返回受影响行数

            cmd = new MySqlCommand(sql, connect());
            int count = cmd.ExecuteNonQuery();
            DBClose();
            return count;
        }
        public string DataOne(string sql)
        {
            //查询一行一列数据
            try
            {
                cmd = new MySqlCommand(sql, connect());
                string value = (string)cmd.ExecuteScalar();
                DBClose();
                return value;
            }
            catch
            {
                return null;
            }

        }
        public int DataValue(string sql)
        {
            //用于登录验证，是否存在指定内容操作

            cmd = new MySqlCommand(sql, connect());
            int count = Convert.ToInt32(cmd.ExecuteScalar());
            DBClose();
            return count;
        }
        public MySqlDataReader DataListAll(string sql)
        {
            //用于查询多条数据
            cmd = new MySqlCommand(sql, connect());
            MySqlDataReader dr = cmd.ExecuteReader();

            DBClose();
            return dr;
        }
        public object[] DataRowOne(string sql)
        {
            MySqlCommand cmd = new MySqlCommand(sql, connect());
            MySqlDataReader dr = cmd.ExecuteReader();

            if (dr.Read())
            {
                int rowCount = dr.FieldCount;
                object[] arr = new object[rowCount];
                int i = 0;
                for (; i < rowCount; i++)
                {
                    arr[i] = dr.GetValue(i);
                }
                return arr;
            }
            DBClose();
            return null;
        }
        public void DBClose()
        {
           
                connect().Close();
                return;
            
        }
    }
}